package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.LogFactory;
import com.block.common.service.impl.ApplicationInfoServiceImpl;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.MobileMd5IsInListUtils;
import com.block.datapush.service.apipush.utils.XinXiaoRongUtil;
import com.block.db.entity.*;
import com.block.db.mapper.DataMatchOrderItemMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 信小融
 */
@Service
public class XinXiaoRongApiSMaskPushService implements IPushApiService, IPushApi2Service {

    private static final Logger log = LogFactory.getPushLog();


    @Autowired
    ApplicationInfoServiceImpl applicationInfoService;
    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("apply_name", memberSourceInfo.getRealname());
        paramMap.put("phone_mask", memberSourceInfo.getMobile().substring(0, 8));
        paramMap.put("sex", XinXiaoRongUtil.getSex(memberSourceInfo.getSex()));
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        paramMap.put("province",memberSourceInfo.getCityCode());
        paramMap.put("loan", XinXiaoRongUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("loan_term", XinXiaoRongUtil.getloantime(memberSourceInfo.getLoanTime()));
        paramMap.put("has_social", XinXiaoRongUtil.getSheBao(memberSourceInfo.getShebao()));
        paramMap.put("has_fund", XinXiaoRongUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("house_property", XinXiaoRongUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("car_property", XinXiaoRongUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("zhima_credit", XinXiaoRongUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("credit_card_limit", XinXiaoRongUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("huabei", XinXiaoRongUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("professional", XinXiaoRongUtil.getGongzuo(memberSourceInfo.getGongzuo()));
        paramMap.put("enterprise_license", "0");
        paramMap.put("equipment", "iPhone");

        String jsonString = JSON.toJSONString(paramMap);
        String encrypt = getAesEncrypt(jsonString,pushApiKeyParam.getApiSecret());
        Map<String, Object> aceMap = new HashMap<>();
        aceMap.put("channel",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);

        log.info("【信小融全流程】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{}", queryUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【信小融全流程】撞库结束【result】{}", result);


        JSONObject resultObject = JSON.parseObject(result);
        Integer status = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(status + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(status), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            JSONArray md5s = data.getJSONArray("md5s");
            String mobileMd5 = memberSourceInfo.getMobileMd5();
            if(MobileMd5IsInListUtils.isMobileMd5InList(md5s, mobileMd5)){
                //如果存在
                pushApiResult.setPushSuccess(false);
                pushApiResult.setCode(status+ "|" + "500");
                pushApiResult.setMessage(msg + "|" + mobileMd5 +"已存在");
                return pushApiResult;
            }

            String logo = data.getString("logo");
            String productName = data.getString("product_name");
            String orgName = data.getString("company_name");
            String order_no = data.getString("order_no");
            extJson.put("order_no",order_no);
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("productName",productName);
            infoObject.put("orderNo",orderNo);
            infoObject.put("productId",order_no);
            infoObject.put("companyName",orgName);
            infoObject.put("companyLogo",logo);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = data.getJSONArray("agreements");
            if (protocolList.size() != 0){
                for (Object o : protocolList) {
                    JSONObject jsonObject1 = new JSONObject();
                    String s = JSONObject.toJSONString(o);
                    JSONObject jsonObject = JSON.parseObject(s);
                    String protocolName = jsonObject.getString("protocolName");
                    String protocolUrl = jsonObject.getString("protocolUrl");
                    jsonObject1.put("protocalName",protocolName);
                    jsonObject1.put("protocalUrl",protocolUrl);
                    jsonArray.add(jsonObject1);
                }
            }
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if(ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                String price1 = data.getString("price");
                BigDecimal price = new BigDecimal(price1);
                if(price == null || price.compareTo(new BigDecimal(0.00))== -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceRight = typeRate.multiply(price);
                pushApiResult.setPrice(price);
                pushApiResult.setPriceRight(priceRight);
            }
            return pushApiResult;
        }



        return pushApiResult;
    }

    private String getAesEncrypt(String data, String apiSecret) throws Exception {
        byte[] keyBytes = apiSecret.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        // 创建Cipher实例
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 执行加密
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // 将加密后的数据转换为Base64字符串
        return  Base64.getEncoder().encodeToString(encryptedData);
    }


    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String order_no = extJson.getString("order_no");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("order_no", order_no);
        paramMap.put("apply_name", memberSourceInfo.getRealname());
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("sex", XinXiaoRongUtil.getSex(memberSourceInfo.getSex()));
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        paramMap.put("province",memberSourceInfo.getCityCode());
        paramMap.put("loan", XinXiaoRongUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("loan_term", XinXiaoRongUtil.getloantime(memberSourceInfo.getLoanTime()));
        paramMap.put("has_social", XinXiaoRongUtil.getSheBao(memberSourceInfo.getShebao()));
        paramMap.put("has_fund", XinXiaoRongUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("house_property", XinXiaoRongUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("car_property", XinXiaoRongUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("zhima_credit", XinXiaoRongUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("credit_history", XinXiaoRongUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("credit_card_limit", XinXiaoRongUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("huabei", XinXiaoRongUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("professional", XinXiaoRongUtil.getGongzuo(memberSourceInfo.getGongzuo()));
        paramMap.put("enterprise_license", "0");
        paramMap.put("equipment", "iPhone");

        String orderId = extJson.getString("orderId");
        String orderItemId = extJson.getString("orderItemId");
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        paramMap.put("agreement_url", protocolUrl);

        String jsonString = JSON.toJSONString(paramMap);
        String encrypt =  getAesEncrypt(jsonString,pushApiKeyParam.getApiSecret());

        Map<String, Object> aceMap = new HashMap<>();
        aceMap.put("channel",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);

        log.info("【信小融全流程】导单开始【requestUrl】{}【paramMap】{}【aceMap】{}", requestUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【信小融全流程】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(code.toString());
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if(StrUtil.equals(String.valueOf(code), "200")){
            thirdInfoDTO.setStatus("SUCCESS");
        }

        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        return null;

    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        return null;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }


    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("apply_name", memberSourceInfo.getRealname());
        paramMap.put("phone_mask", memberSourceInfo.getMobileMask());
        paramMap.put("sex", XinXiaoRongUtil.getSex(memberSourceInfo.getSex()));
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        paramMap.put("province",memberSourceInfo.getCityCode());
        paramMap.put("loan", XinXiaoRongUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("loan_term", XinXiaoRongUtil.getloantime(memberSourceInfo.getLoanTime()));
        paramMap.put("has_social", XinXiaoRongUtil.getSheBao(memberSourceInfo.getShebao()));
        paramMap.put("has_fund", XinXiaoRongUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("house_property", XinXiaoRongUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("car_property", XinXiaoRongUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("zhima_credit", XinXiaoRongUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("credit_history", XinXiaoRongUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("credit_card_limit", XinXiaoRongUtil.getXinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("huabei", XinXiaoRongUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("professional", XinXiaoRongUtil.getGongzuo(memberSourceInfo.getGongzuo()));
        paramMap.put("enterprise_license", "0");
        paramMap.put("equipment", "iPhone");

        String jsonString = JSON.toJSONString(paramMap);
        String encrypt = getAesEncrypt(jsonString,pushApiKeyParam.getApiSecret());
        Map<String, Object> aceMap = new HashMap<>();
        aceMap.put("channel",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);

        log.info("【信小融半流程分润】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{}", queryUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【信小融半流程分润】撞库结束【result】{}", result);


        JSONObject resultObject = JSON.parseObject(result);
        Integer status = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(status + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(status), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            JSONArray md5s = data.getJSONArray("md5s");


            String logo = data.getString("logo");
            String productName = data.getString("product_name");
            String orgName = data.getString("company_name");
            String planId = data.getString("plan_id");
            extJson.put("planId",planId);
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(orderNo);
            JSONObject infoObject = new JSONObject();
            infoObject.put("productName",productName);
            infoObject.put("orderNo",orderNo);
            infoObject.put("productId",planId);
            infoObject.put("companyName",orgName);
            infoObject.put("companyLogo",logo);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = data.getJSONArray("agreements");
            if (protocolList.size() != 0){
                for (Object o : protocolList) {
                    JSONObject jsonObject1 = new JSONObject();
                    String s = JSONObject.toJSONString(o);
                    JSONObject jsonObject = JSON.parseObject(s);
                    String protocolName = jsonObject.getString("protocolName");
                    String protocolUrl = jsonObject.getString("protocolUrl");
                    jsonObject1.put("protocalName",protocolName);
                    jsonObject1.put("protocalUrl",protocolUrl);
                    jsonArray.add(jsonObject1);
                }
            }
            pushApiResult.setMd5List(md5s);
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if(ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                String price1 = data.getString("price");
                BigDecimal price = new BigDecimal(price1);
                if(price == null || price.compareTo(new BigDecimal(0.00))== -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceRight = typeRate.multiply(price);
                pushApiResult.setPrice(price);
                pushApiResult.setPriceRight(priceRight);
            }
            return pushApiResult;
        }



        return pushApiResult;
    }
}
